<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0px;
            top: 0px;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background: blue;
            position: absolute;
            left: 50px;
            top: 200px;
        }
    </style>
</head>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        var box1Ele = document.querySelector(".box1");

        // 实现box2的拖拽效果；
        var box2Ele = document.querySelector(".box2");
        box2Ele.onmousedown = function(e){
            var x = e.clientX - this.offsetLeft;
            var y = e.clientY - this.offsetTop;
            this.onmousemove = function(e){
                var xx = e.clientX;
                var yy = e.clientY;
                this.style.left = xx- x + "px";
                this.style.top = yy- y + "px";

            }
            this.onmouseup = function(){
                this.onmousemove = "";
            }
        }



        let speed = 5;
        var flag = true;
        setInterval(function () {
            // 先获取元素原本的left值 然后再加一个速度值；
            // 获取非行间样式；
            var leftNum = parseInt(getComputedStyle(box1Ele, null)['left']);
            // console.log(leftNum);
            var dis = window.innerWidth - box1Ele.offsetWidth;
            // console.log(dis);
           
            if(leftNum>=dis){
                speed *=-1;
            }

            if(leftNum<0){
                speed *=-1;
            }
           
           

            var res = leftNum + speed;
           
            box1Ele.style.left = res + "px";

             // 碰撞检测
            if(
                Math.abs( box1Ele.offsetLeft-box2Ele.offsetLeft) <box1Ele.offsetWidth &&
                Math.abs( box1Ele.offsetTop-box2Ele.offsetTop) <box1Ele.offsetHeight
            ){
                console.log("碰了");
                if(flag){
                    speed *=-1
                    flag = false;
                    setTimeout(function(){
                        flag = true;
                    }, 500);
                }
               
            }


        }, 20);





    </script>
</body>

</html>